<template>
  <div class="post-list-container">
    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="posts.length === 0 && !loading" class="empty-state">
      <p>还没有帖子，发布第一条吧！</p>
      <router-link to="/create" class="create-btn">发布帖子</router-link>
    </div>

    <!-- 多列容器 -->
    <div v-else class="masonry">
      <div class="post-card" v-for="post in posts" :key="post.id" @click="goToPostDetail(post.id)" style="cursor: pointer;">
        <div class="post-header">
          <div class="user-info">
            <div class="avatar">
              <img v-if="post.userAvatar" :src="$http.defaults.baseURL + post.userAvatar" :alt="post.username" class="avatar-image">
              <span v-else>{{ post.username ? post.username.charAt(0) : '?' }}</span>
            </div>
            <span class="username">@{{ post.username || '未知用户' }}</span>
          </div>
          <span class="timestamp">{{ formatDate(post.timestamp) }}</span>
        </div>

        <!-- 多张图片显示 -->
        <div class="post-images" v-if="post.images && post.images.length > 0">
          <div class="image-grid" :class="getImageGridClass(post.images.length)">
            <img v-for="(image, index) in getDisplayImages(post.images)" 
                 :key="index" 
                 :src="$http.defaults.baseURL.replace(/\/$/, '') + image" 
                 alt="帖子图片" 
                 class="post-image-item">
          </div>
          <div v-if="post.images.length > 4" class="more-images-overlay">
            +{{ post.images.length - 4 }}
          </div>
        </div>
        <div class="image-placeholder" v-else-if="post.image">
          <!-- 兼容旧数据 -->
          <img :src="$http.defaults.baseURL.replace(/\/$/, '') + post.image" alt="帖子图片" class="post-image">
        </div>
        <div class="image-placeholder" v-else>无图片</div>

        <div class="post-content">
          <h3 class="post-title">{{ post.title || '无标题' }}</h3>
          <p class="post-text">{{ post.content || '无内容' }}</p>
          
          <!-- 标签显示 -->
          <div class="post-tags" v-if="post.tags && post.tags.length > 0">
            <span v-for="(tag, index) in post.tags.slice(0, 3)" :key="index" class="tag-item">
              #{{ tag }}
            </span>
            <span v-if="post.tags.length > 3" class="tag-more">+{{ post.tags.length - 3 }}</span>
          </div>
        </div>

        <div class="post-actions">
          <button class="action-btn">
            <i class="icon like-icon">❤️</i>
            <span>{{ post.likes || 0 }}</span>
          </button>
          <button class="action-btn">
            <i class="icon comment-icon">💬</i>
            <span>评论</span>
          </button>
          <button class="action-btn">
            <i class="icon share-icon">↗️</i>
            <span>分享</span>
          </button>
        </div>
      </div>
    </div>

    <router-link to="/create" class="create-post-btn">
      <span>+</span>
    </router-link>
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: [],
      loading: true
    }
  },
  async created() {
    await this.loadPosts();
  },
  methods: {
    async loadPosts() {
      this.loading = true;
      try {
        const res = await this.$http.get('/api/posts');
        this.posts = res.data;
      } catch (error) {
        console.error('加载帖子失败:', error);
        alert('加载帖子失败，请刷新重试');
      } finally {
        this.loading = false;
      }
    },
    formatDate(timestamp) {
      if (!timestamp) return '';
      try {
        const date = new Date(timestamp);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      } catch (e) {
        return '';
      }
    },
    goToPostDetail(postId) {
      this.$router.push({ name: 'PostDetail', params: { id: postId } });
    },
    getDisplayImages(images) {
      // 在列表页最多显示4张图片
      return images.slice(0, 4);
    },
    getImageGridClass(imageCount) {
      // 根据图片数量调整网格布局
      if (imageCount === 1) return 'grid-1';
      if (imageCount === 2) return 'grid-2';
      if (imageCount === 3) return 'grid-3';
      return 'grid-4'; // 4张或更多
    }
  }
}
</script>

<style scoped>
/* ========== 多列核心 ========== */
.post-list-container {
  max-width: 960px;          /* 放宽最大宽度，方便多列 */
  margin: 0 auto;
  padding: 10px;
}

.masonry {
  column-gap: 20px;
  /* 响应式列数 */
  column-count: 1;
}
@media (min-width: 600px) {
  .masonry { column-count: 2; }
}
@media (min-width: 900px) {
  .masonry { column-count: 3; }
}

.post-card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  break-inside: avoid;   /* 关键：防止卡片被中断 */
}

/* 其余样式保持原样，仅把原来 .post-list-container 下的 .post-card 上移一层即可 */
.loading {
  text-align: center;
  padding: 20px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state p {
  margin-bottom: 20px;
  color: #666;
}

.create-btn {
  display: inline-block;
  padding: 10px 20px;
  background: #ff2449;
  color: white;
  border-radius: 5px;
  text-decoration: none;
  font-weight: bold;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 32px;
  height: 32px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
  margin-right: 8px;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.username {
  font-weight: 500;
}

.timestamp {
  color: #999;
  font-size: 12px;
}

/* 多张图片显示样式 */
.post-images {
  position: relative;
  width: 100%;
}

.image-grid {
  display: grid;
  gap: 2px;
  width: 100%;
}

.grid-1 {
  grid-template-columns: 1fr;
  height: 400px;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
  height: 200px;
}

.grid-3 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  height: 300px;
}

.grid-3 .post-image-item:first-child {
  grid-row: span 2;
}

.grid-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  height: 300px;
}

.post-image-item {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.more-images-overlay {
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 50%;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
}

/* 兼容旧数据 */
.post-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 400px;
  background: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
}

.post-content {
  padding: 15px;
}

.post-title {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.post-text {
  margin: 0;
  color: #333;
  line-height: 1.6;
}

/* 标签样式 */
.post-tags {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-item {
  background: #fff5f7;
  color: #ff2449;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.tag-more {
  background: #f5f5f5;
  color: #999;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
}

.action-btn {
  background: none;
  border: none;
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #666;
}

.action-btn span {
  margin-left: 5px;
}

.icon {
  font-size: 18px;
}

.create-post-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 60px;
  height: 60px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  font-size: 30px;
  box-shadow: 0 4px 10px rgba(255, 36, 73, 0.3);
}
</style>